<template>
  <div>
    <el-popover
      ref="popover"
      :placement="config.placement"
      :title="config.title"
      :width="config.width"
      :trigger="config.trigger"
      :content="config.content"
      popper-class="popowin"
      :disabled="visible"
      :popper-options="{ boundariesElement: 'viewport', removeOnDestroy: true }"
    >
      <el-row :gutter="config.gutter" v-if="list.length > 0 && popoverType">
        <el-col
          :span="config.span"
          v-for="item in list"
          :key="item.serviceOfferId"
        >
          <span @click="OnchangeTap(item)">{{ item.serviceOfferName }}</span>
        </el-col>
      </el-row>
      <div v-else-if="billType" style="text-align: center">
        <el-button
          type="text"
          size="mini"
          @click="accepTance(50030003)"
          class="buttonPopover"
        >
          订 单
        </el-button>
        <el-button
          type="text"
          size="mini"
          @click="accepTance(50030002)"
          class="buttonPopover"
        >
          需求单
        </el-button>
      </div>
      <p v-else>暂无任务</p>
      <el-button
        type="primary"
        slot="reference"
        class="ne-popver-btn"
        @click="queryOldInterfaceBill(row)"
        >{{ config.name }}</el-button
      >
    </el-popover>
    <change-ppm :changeConfig="changeConfig" :row="row"></change-ppm>
  </div>
</template>

<script>
import OrderService from "@/api/order/OrderService.js";
import ChangePpm from "@/components/order/ChangePpm";
import { mapState, mapGetters } from "vuex";
export default {
  components: {
    ChangePpm,
  },
  computed: {
    ...mapState("user", ["user"]),
    ...mapState("orders", ["orderPosInfo"]),
  },
  props: {
    config: {
      type: Object,
      default: () => {
        return {};
      },
    },
    row: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },

  data() {
    return {
      //服务列表
      list: [],
      changeConfig: {
        //变更弹窗
        width: "80%", //弹窗宽度
        title: "速率变更", //弹窗标题
        dialogFormVisible: false, //是否显示 Dialog弹窗
        center: true, //内容是否居中
      },
      visible: true, //弹窗是否显示
      popoverType: true,
      billType: false, //订单需求单浮窗
    };
  },
  methods: {
    //点击正常变更校验
    async queryOldInterfaceBill(row) {
      this.visible = true
      if (this.config.modType == 50200002) {
        this.editRow(row);
      } else {
        let response = await OrderService.queryOldInterfaceBill({
          prodOfferInstIds: row.offerInstId,
        });
        if (response.code == 200) {
          if (response.meta.CODE == 0) {
            if (response.meta.returnJson.count == 0) {
              this.editRow(row);
            } else {
              this.$alert("在老系统有在途变更单,不能再发起变更!", "提示", {
                type: "warning",
              });
            }
          } else {
            // this.$confirm(response.meta.MSG, "提示", {
            //   confirmButtonText: "确定",
            //   type: "warning",
            // })
            //   .then(() => {
                  this.editRow(row);
              // })
              // .catch(() => {});
          }
        } else {
          this.editRow(row);
        }
      }
    },
    //点击修改事件
    async editRow(row) {

      if (this.config.name == "批量改单") {
        if (row.orderItemId == "" || !row.orderItemId) {
          this.$alert("请选择至少一条单据", "警告", {
            type: "warning",
            confirmButtonText: "关闭",
          });
          return;
        }
      }

      if (this.config.name == "批量变更") {
        if (row.offerInstId == "" || !row.offerInstId) {
          this.$alert("请选择至少一条单据", "警告", {
            type: "warning",
            confirmButtonText: "关闭",
          });
          return;
        }
      }

      //重置浮窗
      this.popoverType = this.popoverType ? true : true;

       //继续改单时，上一个页面左上角表单的custSoNumber
      let newCustSoNumber = "";

      let parentFormModel = sessionStorage.getItem('FormModel');

      if(parentFormModel){
        let pCustSoNumber = JSON.parse(parentFormModel).custSoNumber;
        if(pCustSoNumber){
          newCustSoNumber = pCustSoNumber+"";
        }
      }

      //非正常变更前置规则埋点
      var ruleParam;
      if (this.config.modType == 50200002) {
        ruleParam = [
          {
            PUB_REQ: {
              TYPE: "GOVCRM.ORDERSET.FChangePreCheck",
            },
            FCHANGE_BEFORE_CHECK: {
              CUST_ID: row.custId + "",
              ORDER_ITEM_IDS: this.row.orderItemId + "", //协作单ID 多个逗号分隔
              PRODUCT_ID: this.row.prodId + "", //产品ID
            },
          },
        ];
      } else {
        // alert("正常变更前置");
        ruleParam = [
          {
            PUB_REQ: {
              TYPE: "GOVCRM.ORDERSET.NChangePreCheck",
            },
            INSTS: {
              CUST_ID: row.custId + "",
              PROD_OFFER_ID: row.offerId + "",
              CUST_SO_NUMBER: row.custSoNumber + "",
              PROD_OFFER_INST_IDS: row.offerInstId + "",
              PROD_OFFER_INST_LENGTH: row.offerInstId.split(",").length + "", //销售品实例个数
              NEW_CUST_SO_NUMBER: newCustSoNumber
            },
          },
        ];
      }
      //调用规则平台
      const result = await OrderService.rulePlatfromCheck(ruleParam);
      // alert(JSON.stringify(result));
      let ruleCode = result.code;
      let ruleMsg = result.msg;
      //直接通过校验
      // ruleCode = 0; //规则平台的接口暂时不同,阻塞流程,先注掉
      if (ruleCode == 0) {
        //直接校验通过继续之前逻辑
        //改单列表

        let params = {
          prodId: this.row.prodId ? this.row.prodId : 80008007,
          modType: this.config.modType, //非正常变更50200002，正常变更50200003
          orderStage: row.lastStateCd,
        };
        let result = await this.getModifyList(params);

        if (result.code == 200) {
          this.visible = false;
          this.$refs.popover.doShow();
          // this.list = result.meta.prodServiceOffers;
          let prodServiceOffers = result.meta.prodServiceOffers;
          this.list = this.unique(prodServiceOffers);
          this.$refs.popover.updatePopper();
        }
      } else {
        //校验结果有警告或者拒绝，弹窗提示
        //图标样式
        let iconType = "warning";
        if (ruleCode == 2) {
          iconType = "error";
        }
        this.$confirm(ruleMsg, "提示", {
          confirmButtonText: "确定",
          type: iconType,
        })
          .then(async () => {
            //不是拒绝执行（提醒或异常）
            if (ruleCode != 2) {
              //继续之前逻辑
              //改单列表

              let params = {
                prodId: this.row.prodId ? this.row.prodId : 80008007,
                modType: this.config.modType, //非正常变更50200002，正常变更50200003
                orderStage: row.lastStateCd,
              };
              let result = await this.getModifyList(params);

              if (result.code == 200) {
                this.visible = false;
                this.$refs.popover.doShow();
                // this.list = result.meta.prodServiceOffers;
                let prodServiceOffers = result.meta.prodServiceOffers;
                this.list = this.unique(prodServiceOffers);
                this.$refs.popover.updatePopper();
              }
            }
          })
          .catch(() => {});
      }
    },

    unique(newarr) {
      //数组去重
      const res = new Map();
      return newarr.filter(
        (item) =>
          !res.has(item.serviceOfferName) && res.set(item.serviceOfferName, 1)
      );
    },

    async getModifyList(params) {
      //获取服务列表
      let result = await OrderService.getModifyServe(params);
      return result;
    },


    //点击非变正变浮动列表
    async OnchangeTap(item) {

      this.$refs.popover.doClose();
      var ruleParam;
      //继续改单时，上一个页面左上角表单的custSoNumber
      let newCustSoNumber = "";

      let parentFormModel = sessionStorage.getItem('FormModel');

      if(parentFormModel!=null&&parentFormModel){
        let pCustSoNumber = JSON.parse(parentFormModel).custSoNumber;
        if(pCustSoNumber){
          newCustSoNumber = pCustSoNumber+"";
        }
      }


      if (this.config.modType == 50200002) {
        //非正常变更规则埋点1
        ruleParam = [
          {
            PUB_REQ: {
              TYPE: "GOVCRM.ORDERSET.FChangeCheck",
            },
            //todo参数取不到，晶晶姐说先这样放着
            FCHANGE_CHECK: {
              CUST_ID: this.row.custId + "",
              SERVICE_OFFER_ID: item.serviceOfferId + "", //要办理的业务编码
              SERVICE_OFFER_NAME: item.serviceOfferName, //业务名称
              CUST_SO_NUMBER: this.row.custSoNumber + "",
              NEW_CUST_SO_NUMBER: newCustSoNumber,
              PRODUCT_ID: this.row.prodId + "",
              ORDER_ITEM_LEN: (this.row.orderItemId + '').split(",").length + "", //协作单数量
              ORDER_ITEM_IDS: this.row.orderItemId + "", //协作单逗号分割
              ORDER_STAGE: this.row.lastStateCd + "", //订单类型
              ORG_ID: this.user.orgId + "", //部门ID
              OFFER_ID: this.row.offerId + "", //销售品ID
              OFFER_INST_IDS: this.row.offerInstId + "", //销售品实例ID 多个时逗号分隔
              ACC_NUM: this.row.accNum ? this.row.accNum + "" : "", //业务号码  多个时逗号分隔
              DEPARTMENT_ID: this.user.departmentId + "",

            },
          },
        ];
      } else {
        //正常变更规则埋点
        ruleParam = [
          {
            PUB_REQ: {
              TYPE: "GOVCRM.ORDERSET.NChangeCheck",
            },
            INSTS: {
              CUST_ID: this.row.custId + "",
              ORG_ID: this.user.orgId + "",
              DEPARTMENT_ID: this.user.departmentId + "",
              SERVICE_OFFER_NAME: item.serviceOfferName,
              PROD_OFFER_INST_LENGTH:
                this.row.offerInstId.split(",").length + "", //销售品实例个数
              STAFF_ID: this.user.staffId + "",
              NEW_CUST_SO_NUMBER: newCustSoNumber,
              PROD_OFFER_ID: this.row.offerId + "",
              CUST_SO_NUMBER: this.row.custSoNumber + "",
              TYPE: this.config.name == "正常变更" ? "1" : "2", //1单个2批量
              DK_PRODUCT: this.row.prodId + "", //同PRODUCT_ID
              REGION_TYPE: this.user.regionType + "", //区域类型 1000集团，1100省，1300市，1400县
              SERVICE_OFFER_ID: item.serviceOfferId + "",
              SERVICE_OFFER_IDD: item.serviceOfferId + "",
              PROD_OFFER_INST_IDS: this.row.offerInstId + "",
              PRODUCT_ID: this.row.prodId + "",
              CUST_NAME: this.orderPosInfo.custMsg.custName,
              LAST_ORDER_ITEM_ID: this.row.lastOrderItemId + "",
            },
          },
        ];
      }

      this.changeConfig.selectBill = item.handleStateCd;
      localStorage.setItem("changeConfig", JSON.stringify(this.changeConfig));
      if(this.config.name == "批量变更"){
        sessionStorage.setItem('isBatchchange',true);//批量变更标识
      }else {
        sessionStorage.removeItem('isBatchchange');
      }
      //调用规则平台
      const result = await OrderService.rulePlatfromCheck(ruleParam);
      // alert(JSON.stringify(result));
      let ruleCode = result.code;
      let ruleMsg = result.msg;
      //直接通过校验
      // ruleCode = 0; //规则平台的接口暂时不同,阻塞流程,先注掉
      if (ruleCode == 0) {
        //直接校验通过继续之前逻辑
        this.changeConfig.title = item.serviceOfferName;
        let ppmCondition = {
          productId: this.row.prodId ? this.row.prodId : 80008007,
          serviceOfferId: item.serviceOfferId,
          modType: this.config.modType,
          optionId: this.config.modType == "50200002" ? "21" : "32",
        };
        sessionStorage.setItem("ppmCondition", JSON.stringify(ppmCondition));
        if (this.config.modType == 50200003) {
          //modType为50200003时-销售品信息_正常变更事件，为50200002时-在途订单_改单事件
          //50030002为需求单，需要弹窗，50030003为订单不需要弹窗
          if (
            item.handleStateCd == 50030002 &&
            item.serviceOfferName == "发起局变更"
          ) {
            this.changeConfig.dialogFormVisible = true;
          } else if (item.handleStateCd == 50030002) {
            this.$refs.popover.doShow();
            this.popoverType = false;
            this.billType = true;
            this.changeConfig.dialogFormVisible = false;
          } else {
            //50030003为订单不需要弹窗，放行
            this.changeConfig.dialogFormVisible = true;
          }
        } else {
          //不为销售品信息_正常变更时候，放行，以此不影响其他界面的使用
          this.changeConfig.dialogFormVisible = true;
        }
      } else {
        //校验结果有警告或者拒绝，弹窗提示
        //图标样式
        let iconType = "warning";
        if (ruleCode == 2) {
          iconType = "error";
        }
        this.$confirm(ruleMsg, "提示", {
          confirmButtonText: "确定",
          type: iconType,
          showCancelButton: false,
        })
          .then(async () => {
            //不是拒绝执行（提醒或异常）
            if (ruleCode != 2) {
              //继续之前逻辑
              this.changeConfig.title = item.serviceOfferName;
              let ppmCondition = {
                productId: this.row.prodId ? this.row.prodId : 80008007,
                serviceOfferId: item.serviceOfferId,
                modType: this.config.modType,
                optionId: this.config.modType == "50200002" ? "21" : "32",
              };
              sessionStorage.setItem(
                "ppmCondition",
                JSON.stringify(ppmCondition)
              );
              if (this.config.modType == 50200003) {
                //modType为50200003时-销售品信息_正常变更事件，为50200002时-在途订单_改单事件
                //50030002为需求单，需要弹窗，50030003为订单不需要弹窗
                if (
                  item.handleStateCd == 50030002 &&
                  item.serviceOfferName == "发起局变更"
                ) {
                  this.changeConfig.dialogFormVisible = true;
                } else if (item.handleStateCd == 50030002) {
                  this.$refs.popover.doShow();
                  this.popoverType = false;
                  this.billType = true;
                  this.changeConfig.dialogFormVisible = false;
                } else {
                  //50030003为订单不需要弹窗，放行
                  this.changeConfig.dialogFormVisible = true;
                }
              } else {
                //不为销售品信息_正常变更时候，放行，以此不影响其他界面的使用
                this.changeConfig.dialogFormVisible = true;
              }
            }
          })
          .catch(() => {});
      }
    },
    accepTance(id) {
      this.changeConfig.dialogFormVisible = true;
      this.changeConfig.selectBill = id;
      localStorage.setItem("changeConfig", JSON.stringify(this.changeConfig));
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .ne-popver-btn{
  width: auto;
  padding: 0 .08rem;
  span {
    font-size: .12rem;
  }
}
.popowin {
  span {
    cursor: pointer;
    line-height: 0.3rem;
    color: $textColor1;
    text-align: center;
    position: relative;
    padding-left: 0.1rem;
    display: inline-block;
    &::before {
      position: absolute;
      top: 40%;
      left: 0;
      content: "";
      width: 0.05rem;
      height: 0.05rem;
      border-radius: 50%;
      background: $textColor1;
    }
    &:hover {
      color: $blue;
    }
  }
}
.buttonPopover {
  color: #333;
  width: 80px;
  :hover {
    color: #0052d9;
  }
}
</style>
